#coding:utf-8
#Author Robin Wang Li xin
#Email:Luobintianya@gmail.com
#copyright: datiandou.com
from django.http import HttpRequest
from django.http import HttpResponse
from django.template import Context, loader, RequestContext
from django.template.loader import get_template
from django.shortcuts import render, get_object_or_404, render_to_response, HttpResponseRedirect
from django import http
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from datiandouweb.models import DUploadFile,UserProfile
import json
from django.core.files.uploadedfile import UploadedFile
from datiandou import settings
import uuid
import logging
import os
from datetime import date,datetime
from django.http import HttpResponse, HttpResponseBadRequest

def get_404(request):
    print("get404")
    #error404=get_template('error/404.html')
    return render_to_response('error/404.html')
    #return http.HttpResponseNotFound(error404.render(RequestContext(request, {'request_path': request.path})))



def authority(view):
    def new_view(request, *args, **kwargs):
        print(args)
        if not request.user.is_authenticated():
            return HttpResponseRedirect('/accounts/login/')
        return view(request, *args, **kwargs)
        return new_view





class AjaxableResponseMixin(object):
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
                }
            return self.render_to_json_response(data)
        else:
            return response
